import Taro, { useLoad, useRouter } from '@tarojs/taro' // 导入 useState 钩子
import { useEffect, useState } from 'react'
import { getGoodDetail } from '@/api/myOrder'
import { addCollectService, cancelCollectService } from '@/api/collect'
import { useSelector } from 'react-redux'
import styles from './index.module.scss'

export interface Data {
  content: string
  coverUrl: string
  description: string
  id: number
  imgs: string[]
  isCollect: boolean
  isOver: boolean
  name: string
  note: string
  price: number
  unit: string
  weight: number
  [property: string]: any
}

export default function ProductDetail() {
  const token = useSelector((state: any) => state.user.token)

  const router = useRouter()
  const [goodDetail, setGoodDetail] = useState<Data>()

  const fetchGetGoodDetail = async (id) => {
    const res = await getGoodDetail(Number(id))
    if (res && res.code === 0) {
      setGoodDetail(res.data.productDetail)
    } else {
      Taro.showToast({
        title: res.msg,
        icon: 'none',
      })
    }
  }

  const addCollect = async () => {
    const { id } = router.params
    try {
      const res = await addCollectService(id)
      if (res.code === 0) {
        Taro.showToast({
          title: ' 添加收藏成功',
          icon: 'none',
        })
        // setGoodDetail((prevState) => ({
        //   ...prevState,
        //   isCollect: true,
        // }))
        //添加成功重新获取详情状态
        fetchGetGoodDetail(id)
      } else {
        Taro.showToast({
          title: ' 添加收藏失败',
          icon: 'none',
        })
      }
    } catch (err) {
      console.log(err)
    }
  }

  const handleAddCollect = () => {
    if (!token) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none',
      })
    } else {
      addCollect()
    }
  }
  //取消收藏
  const cancelCollect = async () => {
    const { id } = router.params
    try {
      const res = await cancelCollectService(parseInt(id as string))
      if (res.code === 0) {
        Taro.showToast({
          title: ' 取消成功',
          icon: 'none',
        })
        // setGoodDetail((prevState) => ({
        //   ...prevState,
        //   isCollect: false,
        // }))
        //取消成功重新获取详情状态
        fetchGetGoodDetail(id)
      } else {
        Taro.showToast({
          title: ' 取消收藏失败',
          icon: 'none',
        })
      }
    } catch (err) {
      console.log(err)
    }
  }

  const back = () => {
    Taro.switchTab({
      url: '/pages/home/index',
    })
  }

  const handelPay = () => {
    //获取仓库token信息
    if (!token) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none',
      })
    } else {
      Taro.navigateTo({
        url: `/pages/newOrder/index?id=${goodDetail?.id}`,
      })
    }
  }

  useLoad(() => {
    console.log('Page loaded.')
    // 获取路由参数id
    const { id } = router.params
    //拉取页面数据
    fetchGetGoodDetail(id)
  })
  useEffect(() => {
    console.log('是否收藏', goodDetail?.isCollect)
  }, [goodDetail?.isCollect])

  return (
    goodDetail && (
      <div className={styles.productDetail}>
        <div className={styles.top}>
          <div className={styles.swiper}>
            <img
              className={styles.swiperImg}
              src={goodDetail?.coverUrl}
              alt=''
            />
          </div>
          <div className={styles.info}>
            <div className={styles.price}>¥ {goodDetail?.price}</div>
            <div className={styles.desc}>{goodDetail?.description}</div>
            <div className={styles.note}>{goodDetail?.note}</div>
            <img
              className={styles.noteImg}
              src={require('../../assets/productdetail/note.png')}
              alt=''
            />
          </div>
          <div className={styles.images}>
            {goodDetail.imgs &&
              goodDetail.imgs.length > 0 &&
              goodDetail.imgs.map((item) => (
                <img key={item} className={styles.ims} src={item} alt='' />
              ))}
          </div>
        </div>
        <div className={styles.footerPart}>
          <div className={styles.icons}>
            <img
              className={styles.img}
              src={require('../../assets/productdetail/image.png')}
              alt=''
              onClick={back}
            />
            {goodDetail.isCollect && (
              <img
                onClick={cancelCollect}
                className={styles.img}
                src={require('../../assets/star.png')}
                alt=''
              />
            )}
            {!goodDetail.isCollect && (
              <img
                onClick={handleAddCollect}
                className={styles.img}
                src={require('../../assets/productdetail/collect.png')}
                alt=''
              />
            )}
          </div>
          {goodDetail.isOver ? (
            <div
              className={styles.noStoreBtn}
              onClick={() =>
                Taro.showToast({ title: '商品已售罄😘', icon: 'error' })
              }
            >
              已售罄
            </div>
          ) : (
            <div className={styles.payBtn} onClick={handelPay}>
              单独购买
            </div>
          )}
        </div>
      </div>
    )
  )
}
